<template>
  <view class="container">
    <view class="flags">
      <view
        class="flag"
        :class="{ 'active-flag': activeFlags.includes(flag) }"
        v-for="(flag, index) in flags"
        :key="index"
        @click="clickFlag(flag)"
        >{{ flag }}</view
      >
      <view
        class="flag"
        v-if="flagTriggerText != null"
        :class="{ 'active-flag': textareaVisibility }"
        @click="textareaVisibility = !textareaVisibility"
      >
        <uni-icons type="compose" size="16"></uni-icons>
        {{ flagTriggerText }}
      </view>
    </view>
    <view class="text" v-show="textareaVisibility">
      <textarea :placeholder="placeholder" :style="{ height: textareaHeight }" v-model="textValue" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
const props = defineProps({
  flags: {
    type: Object as () => string[],
    default: [] as String[]
  },
  flagTriggerText: {
    type: String,
    default: undefined // 如果没有值有效字段串值，那将不显示
  },
  placeholder: {
    type: String,
    default: '请输入...'
  },
  textareaHeight: {
    type: String,
    default: '180rpx'
  }
})
const emit = defineEmits<{
  (e: 'change', activeFlags: string[], textValue: string): void
}>()
const activeFlags = ref<string[]>([])
const textValue = ref('')
// 是否显示textarea
const textareaVisibility = ref(props.flagTriggerText == null)
function clickFlag(flag: string) {
  if (activeFlags.value.includes(flag)) {
    for (let i in activeFlags.value) {
      if (activeFlags.value[i] === flag) {
        activeFlags.value.splice(parseInt(i), 1)
      }
    }
  } else {
    activeFlags.value.push(flag)
  }
}
watch(
  () => [activeFlags.value, textValue.value],
  ([_activeFlags, _textValue]) => {
    emit('change', activeFlags.value, textValue.value)
  },
  { immediate: true, deep: true }
)
defineExpose({
  activeFlags,
  textValue
})
</script>

<style scoped lang="scss">
.container {
  width: 100%;

  // 有哪些flags可以先在这里传入
  .flags {
    width: 100%;

    .flag {
      display: inline-block;
      margin-right: 15rpx;
      margin-bottom: 15rpx;
      padding: 10rpx 15rpx;
      font-size: 25rpx;
      border-radius: 8rpx;
      color: #878787;
      background-color: #f6f6f6;
    }

    .active-flag {
      color: #ec8413 !important;
      background-color: #fdf8e2 !important;
    }
  }

  .text {
    padding: 25rpx;
    width: 100%;
    border-radius: 25rpx;
    background-color: #fafafa;
    box-sizing: border-box;
  }
}
</style>
